package com.sx.zongzhi.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.util.SparseArray;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.SpinnerPubAdapter;
import com.sx.zongzhi.bean.GlobalBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OverseasDetailBean;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.bean.ProvinceBean;
import com.sx.zongzhi.bean.PublicBean;
import com.sx.zongzhi.net.ServiceFactory;
import com.sx.zongzhi.presenter.CheckMessagePest;
import com.sx.zongzhi.presenter.OverseasAddPest;
import com.sx.zongzhi.presenter.PublicListPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ProvinceUtils;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.CommentView;
import com.sx.zongzhi.view.ICheckMessageView;
import com.sx.zongzhi.view.IPublicBeanView;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.widget.LoadDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sx.zongzhi.R.string.submit;

/**
 * 添加/编辑境外人员
 */
public class AddOverseasActivity extends BaseActivity implements IPublicBeanView,UploadFileView
                ,CommentView ,ICheckMessageView{

    @BindView(R.id.imv_Head) ImageView imv_Head;
    @BindView(R.id.et_SurName) EditText et_SurName;
    @BindView(R.id.et_Name) EditText et_Name;
    @BindView(R.id.sp_Sex) Spinner sp_Sex;
    @BindView(R.id.tv_Birthday) TextView tv_Birthday;
    @BindView(R.id.sp_CredentialsType) Spinner sp_CredentialsType;
    @BindView(R.id.et_IDCard) EditText et_IDCard;
    @BindView(R.id.tv_NowAddress) TextView tv_NowAddress;
    @BindView(R.id.rg_NowAddress) RadioGroup rg_NowAddress;
    @BindView(R.id.rbt_Yes) RadioButton rbt_Yes;
    @BindView(R.id.rbt_No) RadioButton rbt_No;
    @BindView(R.id.tv_NowAddressTitle) TextView tv_NowAddressTitle;
    @BindView(R.id.et_CurrentAddress) EditText et_CurrentAddress;
    @BindView(R.id.sp_Nationality) Spinner sp_Nationality;
    @BindView(R.id.sp_Aims) Spinner sp_Aims;
    @BindView(R.id.et_Phone) EditText et_Phone;
    @BindView(R.id.et_Telephone) EditText et_Telephone;
    @BindView(R.id.tv_ComeData) TextView tv_ComeData;
    @BindView(R.id.tv_BackData) TextView tv_BackData;
    @BindView(R.id.tv_StartTime) TextView tv_StartTime;
    @BindView(R.id.tv_EndTime) TextView tv_EndTime;
    @BindView(R.id.et_ChainName) EditText et_ChainName;
    @BindView(R.id.rbt_KeyYes) RadioButton rbt_KeyYes;
    @BindView(R.id.rbt_KeyNo) RadioButton rbt_KeyNo;
    @BindView(R.id.sp_ProfessionType) Spinner sp_ProfessionType;
    @BindView(R.id.et_Profession) EditText et_Profession;
    @BindView(R.id.sp_Religion) Spinner sp_Religion;
    @BindView(R.id.et_Service) EditText et_Service;
    private boolean isAdd=false;
    private OptionsPickerView pvOptions;
    private OverseasDetailBean detailBean;
    private String path="";
    private String orgId="";

    private ArrayList<ProvinceBean> provinceList;
    private ArrayList<List<ProvinceBean>> cityList;
    private ArrayList<List<List<ProvinceBean>>> districtList;
    private SparseArray nowAddressId;
    private CheckMessagePest checkMessagePest;
    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_overseas);
        orgId=getIntent().getStringExtra("orgId");
        detailBean= (OverseasDetailBean) getIntent().getSerializableExtra("OverseasDetailBean");
        setTitleRight(submit);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initView() {
        if (detailBean==null){
            setTitleName("境外人员新增");
            isAdd=true;
        }else {
            isAdd=false;
            setTitleName("境外人员修改");
            showView();
        }
        rg_NowAddress.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId==R.id.rbt_Yes){
                    tv_NowAddressTitle.setText("现住门(楼)详址");
                }
                if (checkedId==R.id.rbt_No){
                    tv_NowAddressTitle.setText("无房原因");
                }
            }
        });
    }

    private void initData() {
        new ProvinceUtils().initData(this, new ProvinceUtils.AdapterCallback() {
            @Override
            public void getData(ArrayList<ProvinceBean> provinceList, ArrayList<List<ProvinceBean>> cityList,
                                ArrayList<List<List<ProvinceBean>>> districtList) {
                AddOverseasActivity.this.provinceList=provinceList;
                AddOverseasActivity.this.cityList=cityList;
                AddOverseasActivity.this.districtList=districtList;
                showCity();
            }
        });
        PublicListPest publicListPest=new PublicListPest(this);
        publicListPest.getPublicList("性别");
        publicListPest.getPublicList("证件类型");
        publicListPest.getPublicList("国籍");
        publicListPest.getPublicList("来华目的");
        publicListPest.getPublicList("职业");
        publicListPest.getPublicList("宗教信仰");
    }


    /**
     * 显示地区显示列表
     */
    private void showCity() {
        if (pvOptions==null) {
            pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    // 返回的分别是三个级别的选中位置
                    String tx = provinceList.get(options1).getPickerViewText()+"-"+
                            cityList.get(options1).get(option2).getPickerViewText()+"-"+
                            districtList.get(options1).get(option2).get(options3).getPickerViewText();
                        tv_NowAddress.setText(tx);
                        if (nowAddressId==null){
                            nowAddressId=new SparseArray();
                        }
                        nowAddressId.clear();
                    nowAddressId.put(0,provinceList.get(options1).getId());
                    nowAddressId.put(1,cityList.get(options1).get(option2).getId());
                    nowAddressId.put(2,districtList.get(options1).get(option2).get(options3).getId());

                }
            }).setTitleText("地区选择")
                    .setDividerColor(Color.RED)
                    .setTextColorCenter(Color.RED) //设置选中项文字颜色
                    .setContentTextSize(15)
                    .build();
            pvOptions.setPicker(provinceList, cityList, districtList);
        }

    }


    @OnClick({ R.id.tv_right,R.id.imv_Head,R.id.tv_Birthday,R.id.tv_NowAddress,R.id.tv_ComeData,
            R.id.tv_BackData,R.id.tv_StartTime,R.id.tv_EndTime})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.imv_Head:
                PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())
                    .selectionMode(PictureConfig.SINGLE)
                    .withAspectRatio(1,1)
                    .enableCrop(true)
                    .compress(true)
                    .compressGrade(Luban.CUSTOM_GEAR)
                    .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                    .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.tv_right:
                submit();
                break;
            case R.id.tv_Birthday:
                BaseUtil.createDataPop(this,tv_Birthday);
                break;
            case R.id.tv_NowAddress:
                if (pvOptions!=null){
                    pvOptions.show();
                }
                break;
            case R.id.tv_ComeData:
                BaseUtil.createDataPop(this,tv_ComeData);
                break;
            case R.id.tv_BackData:
                BaseUtil.createDataPop(this,tv_BackData);
                break;
            case R.id.tv_StartTime:
                BaseUtil.createDataPop(this,tv_StartTime);
                break;
            case R.id.tv_EndTime:
                BaseUtil.createDataPop(this,tv_EndTime);
                break;
        }
    }


    private void submit() {
        String surName=et_SurName.getText().toString().trim();
        if (BaseUtil.isEmpty(surName)){
            et_SurName.setError("40字以内");
            ToastUtils.showToast(this,"外文姓");
            return;
        }
        String name=et_Name.getText().toString().trim();
        if (BaseUtil.isEmpty(name)){
            et_Name.setError("40字以内");
            ToastUtils.showToast(this,"外文名");
            return;
        }
        String birthday=tv_Birthday.getText().toString();
        if (BaseUtil.isEmpty(birthday)){
            ToastUtils.showToast(this,"请选择出生日期");
            return;
        }

        String idCard=et_IDCard.getText().toString().trim();
        if (BaseUtil.isEmpty(idCard)){
            et_IDCard.setError("30字以内");
            ToastUtils.showToast(this,"证件号");
            return;
        }

        String nowAddress=tv_NowAddress.getText().toString();
        if (BaseUtil.isEmpty(nowAddress)){
            ToastUtils.showToast(this,"请选择现住址");
            return;
        }
        String currentAddress=et_CurrentAddress.getText().toString().trim();
        if (BaseUtil.isEmpty(currentAddress)) {
            et_CurrentAddress.setError("80字以内");
            ToastUtils.showToast(this,"当前地址");
            return;
        }
        String phone=et_Phone.getText().toString().trim();
        String tel=et_Telephone.getText().toString().trim();
        if (!BaseUtil.isEmpty(phone)&&!BaseUtil.isEmpty(tel)){
            et_Phone.setError("至少输入一种联系方式");
            ToastUtils.showToast(this,"至少输入一种联系方式");
            return;
        }
        String comeData=tv_ComeData.getText().toString();
        if (BaseUtil.isEmpty(comeData)){
            ToastUtils.showToast(this,"请选择到达日期");
            return;
        }
        String backData=tv_BackData.getText().toString();
        if (BaseUtil.isEmpty(backData)){
            ToastUtils.showToast(this,"请选择预计离开日期");
            return;
        }
        String startTime=tv_StartTime.getText().toString();
        String endTime=tv_EndTime.getText().toString();
        if (BaseUtil.isEmpty(startTime)||BaseUtil.isEmpty(endTime)){
            ToastUtils.showToast(this,"请选择证件有效期");
            return;
        }

        GlobalBean sexBean= (GlobalBean) sp_Sex.getSelectedItem();
        if (sexBean==null){
            ToastUtils.showToast(this,"请选择性别");
            return;
        }
        GlobalBean credBean= (GlobalBean) sp_CredentialsType.getSelectedItem();
        if (credBean==null){
            ToastUtils.showToast(this,"请选择证件类型");
            return;
        }
        GlobalBean nBean= (GlobalBean) sp_Nationality.getSelectedItem();
        if (nBean==null){
            ToastUtils.showToast(this,"请选择国籍");
            return;
        }
        GlobalBean aBean= (GlobalBean) sp_Aims.getSelectedItem();
        if (aBean==null){
            ToastUtils.showToast(this,"请选择来华原因");
            return;
        }
        if (detailBean==null){
            detailBean=new OverseasDetailBean();
        }
        detailBean.setForeignName(surName);
        detailBean.setEnglishName(name);
        detailBean.setAddress(nowAddress);
        detailBean.setProvince((String) nowAddressId.get(0));
        detailBean.setCity((String) nowAddressId.get(1));
        detailBean.setDistrict((String) nowAddressId.get(2));
        if (rbt_Yes.isChecked()){
            detailBean.setIsHaveHouse(true);
            detailBean.setCurrentAddress(currentAddress);
        }else {
            detailBean.setIsHaveHouse(false);
            detailBean.setNoHouseReason(currentAddress);
        }
        detailBean.setGender(sexBean);
        detailBean.setBirthday(birthday);
        detailBean.setCertificateType(credBean);
        detailBean.setCertificateNo(idCard);
        detailBean.setNationality(nBean);
        detailBean.setInflowReason(aBean);
        detailBean.setMobileNumber(phone);
        detailBean.setTelephone(tel);
        detailBean.setArrivalTime(comeData);
        detailBean.setLeaveTime(backData);
        detailBean.setCertificateStrartDay(startTime);
        detailBean.setCertificateEndDay(endTime);
        detailBean.setName(et_ChainName.getText().toString().trim());
        detailBean.setIsEmphasis(rbt_KeyYes.isChecked());
        GlobalBean pBean= (GlobalBean) sp_ProfessionType.getSelectedItem();
        detailBean.setProfession(pBean);
        detailBean.setCareerText(et_Profession.getText().toString().trim());
        GlobalBean rBean= (GlobalBean) sp_Religion.getSelectedItem();
        detailBean.setFaith(rBean);
        detailBean.setWorkUnit(et_Service.getText().toString().trim());

        //验证证件
        if (checkMessagePest==null) {
            checkMessagePest = new CheckMessagePest(this);
        }
        LoadDialog.show(this,"验证证件号码");
        if (isAdd){
            checkMessagePest.checkOverseas(idCard,credBean.getId(),orgId,"");
        }else {
            checkMessagePest.checkOverseas(idCard,credBean.getId(),orgId,detailBean.getId());
        }
    }

    private void submitDone() {
        LoadDialog.show(this,"正在提交数据");
        OverseasAddPest addPest=new OverseasAddPest(this);
        if (isAdd){
            addPest.addOverseas("addOverSeaPerson.action","",orgId,path,detailBean);
        }else {
            addPest.addOverseas("updateOverSeaPerson.action",detailBean.getId(),orgId,path,detailBean);
        }

    }

    private void showView() {
        et_SurName.setText(detailBean.getForeignName());
        et_Name.setText(detailBean.getEnglishName());
        tv_Birthday.setText(detailBean.getBirthday());
        et_IDCard.setText(detailBean.getCertificateNo());
        tv_NowAddress.setText(detailBean.getAddress());
        if (nowAddressId==null){
            nowAddressId=new SparseArray();
        }
        nowAddressId.put(0,detailBean.getProvince());
        nowAddressId.put(1,detailBean.getCity());
        nowAddressId.put(2,detailBean.getDistrict());
        if (detailBean.isIsHaveHouse()){
            rbt_Yes.setChecked(true);
            tv_NowAddressTitle.setText("现住门(楼)详址");
            et_CurrentAddress.setText(detailBean.getCurrentAddress());
        }else {
            rbt_No.setChecked(true);
            tv_NowAddressTitle.setText("无住房原因");
            et_CurrentAddress.setText(detailBean.getNoHouseReason());
        }
        et_Phone.setText(detailBean.getMobileNumber());
        et_Telephone.setText(detailBean.getTelephone());
        tv_ComeData.setText(detailBean.getArrivalTime());
        tv_BackData.setText(detailBean.getLeaveTime());
        tv_StartTime.setText(detailBean.getCertificateStrartDay());
        tv_EndTime.setText(detailBean.getCertificateEndDay());
        et_ChainName.setText(detailBean.getName());
        if (detailBean.isIsEmphasis()){
            rbt_KeyYes.setChecked(true);
        }else {
            rbt_KeyNo.setChecked(true);
        }
        et_Profession.setText(detailBean.getCareerText());
        et_Service.setText(detailBean.getWorkUnit());
        path= ServiceFactory.NEW_API_BASE_URL+ File.separator+detailBean.getImgUrl();
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.mipmap.head_default)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
        Glide.with(this)
                .load(path)
                .apply(options)
                .into(imv_Head);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        path = picUrls.get(0).getCompressPath();
                        RequestOptions options = new RequestOptions()
                                .centerCrop()
                                .placeholder(R.mipmap.head_default);
                        Glide.with(this)
                                .load(path)
                                .apply(options)
                                .into(imv_Head);
                    }
                    break;

            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,message);
    }

    @Override
    public void getPublicList(PublicBean publicBean) {
        if ("性别".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getGender() != null) {
                id = detailBean.getGender().getId();
            }
            showSpinner(sp_Sex, publicBean.getDicts(),id);
        }
        if ("证件类型".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getCertificateType() != null) {
                id = detailBean.getCertificateType().getId();
            }
            showSpinner(sp_CredentialsType, publicBean.getDicts(),id);
        }
        if ("国籍".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getNationality() != null) {
                id = detailBean.getNationality().getId();
            }
            showSpinner(sp_Nationality, publicBean.getDicts(),id);
        }
        if ("来华目的".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getInflowReason() != null) {
                id = detailBean.getInflowReason().getId();
            }
            showSpinner(sp_Aims, publicBean.getDicts(),id);
        }
        if ("职业".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getProfession() != null) {
                id = detailBean.getProfession().getId();
            }
            showSpinner(sp_ProfessionType, publicBean.getDicts(),id);
        }
        if ("宗教信仰".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getFaith() != null) {
                id = detailBean.getFaith().getId();
            }
            showSpinner(sp_Religion, publicBean.getDicts(),id);
        }
    }

    private void showSpinner(Spinner spinner, List<GlobalBean> datas, String id) {
        SpinnerPubAdapter adapter=new SpinnerPubAdapter(this,R.layout.item_text,datas);
        spinner.setAdapter(adapter);
        if (!BaseUtil.isEmpty(id)){
            int count=datas.size();
            for (int i=0;i<count;i++){
                if (id.equals(datas.get(i).getId())){
                    spinner.setSelection(i);
                    break;
                }
            }
        }

    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        if (beans!=null&&beans.size()>0){
            path=beans.get(0).getPath();
            submitDone();
        }
    }

    @Override
    public void commentSuccess(Boolean result) {
        LoadDialog.dismiss(this);
        if (result){
            ToastUtils.showToast(this,"保存成功");
            MyRxBus.get().post(new MsgEvent<>("OverseasActivity",2,"成功"));
            finish();
        }else {
            ToastUtils.showToast(this,"操作失败");
        }
    }

    @Override
    public void checkSuccess(Boolean result, String message) {
        if (result){//返回数据(true:存在,false:不存在)
            et_IDCard.setError(message);
        }else {
            if(BaseUtil.isEmpty(path)|| path.startsWith("http")){
                submitDone();
            }else {
                List<File> files=new ArrayList<>();
                files.add(new File(path));
                LoadDialog.show(this,"正在上传头像中...");
                new UploadFilePest(this).uploadFile(this,files);
            }
        }
    }
}
